#!/usr/bin/env python
# -*- coding: utf-8 -*-
import http.client, urllib.parse
import json
import cv2
import base64

def httpPostImg(img,ip = '192.168.1.8',port = 8889):#8889:是ocr的服务器端口,8890:是yolo图像识别服务器的端口,8891:是sma服务器
    # img_path = r'00001.jpg'
    # img = cv2.imread(img_path)
    try:
        retval, buffer = cv2.imencode('.jpg', img)
        jpg_as_bytes = base64.b64encode(buffer)
        jpg_as_str = jpg_as_bytes.decode('ascii')
        json_object=json.dumps({'img_str':jpg_as_str})
        length = len(json_object)
    except:
        print('httppost img erro')
        return None
    retval, buffer = cv2.imencode('.jpg', img)
    jpg_as_bytes = base64.b64encode(buffer)
    jpg_as_str = jpg_as_bytes.decode('ascii')
    json_object=json.dumps({'img_str':jpg_as_str})
    length = len(json_object)
    
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain","Content-Length":str(length)}
    conn = http.client.HTTPConnection(ip, port,timeout=30)
    conn.request('POST', '/ocr', json_object.encode('utf-8'), headers)#往server端发送数据
    response = conn.getresponse()
    stc1 = response.read()#接受server端返回的数据
    # dictmp = json.loads(stc1,ensure_ascii=False)
    dictmp = json.loads(stc1)
    print("-----------------接受server端返回的数据开始----------------")
    print(dictmp)
    print("-----------------接受server端返回的数据结束----------------")
    conn.close()
    if dictmp['erro'] != 0:
        print('get data from %s:%d erro:%d'%(ip,port,dictmp['erro']))
        return None
    return dictmp['data']
def main():
    import cv2
    import os 
    import time
    spth = os.getcwd() + os.sep + 'screenshot.jpg'
    print(spth)
    imImg = cv2.imread(spth)
    starttime = time.time()
    # dat = httpPostImg(imImg,port = 8891)    #sma测试
    # dat = httpPostImg(imImg,port = 8890)  #yolo测试
    dat = httpPostImg(imImg,port = 8889)    #ocr测试
    endtime = time.time()
    print(dat)
    dittime = endtime - starttime
    print('stime:%.3f,etime:%.3f,dtime:%.3f'%(starttime,endtime,dittime))
    time.sleep(3)
if __name__ == '__main__':
    main()
